package edu.java.lectures.lec12.threads.synchronization.dynamic.bank;

public class Kid extends Thread {

    private BankAccount dadyBankAccount;

    public Kid(String name, BankAccount dadyBankAccount) {
	super(name);
	this.dadyBankAccount = dadyBankAccount;
    }

    public Kid(String name, Runnable runnableObj, BankAccount dadyBankAccount) {
	super(runnableObj, name);
	this.dadyBankAccount = dadyBankAccount;
    }

    @Override
    public void run() {
	for (int i = 0; i < 10; i++) {
	    doWithdraw(10);
	    if (dadyBankAccount.getBalance() < 0) {
		System.out.println("account is overdrawn!");
	    }
	}
    }

    private void doWithdraw(double amount) {
	if (dadyBankAccount.getBalance() >= amount) {
	    System.out.println(getName() + " is going to withdraw " + amount);
	    try {
		Thread.sleep(500);
	    } catch (InterruptedException ex) {
	    }
	    dadyBankAccount.withdraw(10);
	    System.out.println(getName() + " completes the withdrawal");
	} else {
	    System.out.println("Not enough in account for " + getName()
		    + " to withdraw " + dadyBankAccount.getBalance());
	}
    }
}
